﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Diagnostics;
using System.Web.UI.HtmlControls;

public partial class Draft : System.Web.UI.Page
{
    public string username { get; set; }
    List<string> teamNames;
    List<Player> players, lineup;
    public List<DraftPick> draftOrder;
    User user;
    GameweekTeam currentTeam;
    JsonParser jsonParser;

    protected void Page_Load(object sender, EventArgs e)
    {
            user = (User)Session["UserSession"];

            if (user != null)
            {
                username = user.username;
            }
            else
            {
                Response.Redirect("~/Account/Login.aspx");
            }

            addTeamsToDropdown();
            addPositionsToDropdown();
            teamNames = new List<string>();
            lineup = new List<Player>();
            jsonParser = new JsonParser();
            getLineup();

            try
            {
                if (user != null)
                {
                    players = jsonParser.getAvailablePlayers(user.username);
                    initPlayers(players);
                    list(players);
                    listDraftOrder();
                    listPlayers();
                }
            }
            catch (NullReferenceException ex)
            {
                Response.Redirect("~/Account/NewTeam.aspx");
            }
            catch (WebException ex)
            {
                Response.Redirect("~/Account/NewTeam.aspx");
            }
   
    }

    private void getLineup()
    {
        currentTeam = jsonParser.getTeam("1", User.Identity.Name);
        lineup.Clear();

        foreach (Player player in currentTeam.keepers)
        {
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.defenders)
        {
            player.position = Position.Defender;
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.midfielders)
        {
            player.position = Position.Midfielder;
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.forwards)
        {
            player.position = Position.Forward;
            lineup.Add(player);
        }
    }



    private void listPlayers()
    {
        int keepers = 0;
        int defenders = 0;
        int midfielders = 0;
        int forwards = 0;

        for (int i = 0; i < lineup.Count; i++ )
        {
            Player player = lineup.ElementAt(i);
            String lastName = formatString(player);

            switch (player.position)
            {
                case Position.Keeper:
                    if (keepers == 0)
                    {
                        updatePlayerInfo(pos0, pos0name, lastName, "keeper");
                    }
                    else if (keepers == 1)
                    {
                        updatePlayerInfo(pos1, pos1name, lastName, "keeper");
                    }
                    keepers++;
                    break;
                case Position.Defender:
                    if (defenders == 0)
                    {
                        updatePlayerInfo(pos2, pos2name, lastName, "defender");
                    }
                    else if (defenders == 1)
                    {
                        updatePlayerInfo(pos3, pos3name, lastName, "defender");
                    }
                    else if (defenders == 2)
                    {
                        updatePlayerInfo(pos4, pos4name, lastName, "defender");
                    }
                    else if (defenders == 3)
                    {
                        updatePlayerInfo(pos5, pos5name, lastName, "defender");
                    }
                    else if (defenders == 4)
                    {
                        updatePlayerInfo(pos6, pos6name, lastName, "defender");
                    }
                    else
                    {
                        updatePlayerInfo(pos7, pos7name, lastName, "defender");
                    }
                    defenders++;
                    break;
                case Position.Midfielder:
                    if (midfielders == 0)
                    {
                        updatePlayerInfo(pos8, pos8name, lastName, "midfielder");
                    }
                    else if (midfielders == 1)
                    {
                        updatePlayerInfo(pos9, pos9name, lastName, "midfielder");
                    }
                    else if (midfielders == 2)
                    {
                        updatePlayerInfo(pos10, pos10name, lastName, "midfielder");
                    }
                    else if (midfielders == 3)
                    {
                        updatePlayerInfo(pos11, pos11name, lastName, "midfielder");
                    }
                    else
                    {
                        updatePlayerInfo(pos12, pos12name, lastName, "midfielder");
                    }
                    midfielders++;
                    break;
                case Position.Forward:
                    if (forwards == 0)
                    {
                        updatePlayerInfo(pos13, pos13name, lastName, "forward");
                    }
                    else if (forwards == 1)
                    {
                        updatePlayerInfo(pos14, pos14name, lastName, "forward");
                    }
                    else
                    {
                        updatePlayerInfo(pos15, pos15name, lastName, "forward");
                    }
                    forwards++;
                    break;
                default:
                    break;
            }
            //addToLineup(player);
        }
    }

    private void updatePlayerInfo(HtmlGenericControl divShirt, HtmlGenericControl divName, String lastName, String position)
    {
        divName.InnerHtml = lastName;
        divName.Attributes.Add("class", position);
        divShirt.Attributes.Remove("class");
        divShirt.Attributes.Add("class", "shirt picked");
    }

    private static String formatString(Player player)
    {
        String[] splitName = player.playerName.Split(null);
        String lastName = player.playerName;
        if (splitName.Length > 1)
        {
            lastName = lastName.Substring(0, 1) + "." + splitName[1];
        }
        return lastName;
    }

    private void listDraftOrder()
    {
        draftOrder = jsonParser.getDraft(user.username);

        int numberOfPlayers = draftOrder.Count / 16;

        string html = "";
        string header = "";
        for (int j = 1; j < 17; j++)
        {
            html = "";
           header = "<div class='roundheader'>ROUND " + j + "</div>";
            for (int i = 0; i < numberOfPlayers; i++)
            {
                string start = " <span class='draftpick'>Waiting</span>";
                string player = "<span style='float:left; padding-left: 8px;'>";
                int index = (i + j * numberOfPlayers) - (numberOfPlayers);
                string playerName = "";
                try
                {
                    string[] playerN = draftOrder.ElementAt(index).playerName.Split(' ');
                    if (playerN.Length > 1)
                    {
                        playerName = playerN[1];
                    }
                    else
                    {
                        playerName = playerN[0];
                    }

                    if (!draftOrder.ElementAt(index).playerName.Equals(null) && !draftOrder.ElementAt(index).playerName.Equals(""))
                    {
                        playerName = "<span style='float:left'>" + playerName  + "</span>";
                    }
                }
                catch (Exception e)
                {
                }
                if (draftOrder.ElementAt(index).active == 1)
                {
                    start = " <span class='active'>Is drafting</span>";
                    player = "<span class='activePlayer' style='float:left; padding-left: 8px;'>";
                }

                html += player + "Draft " + (index + 1) + " - " + draftOrder.ElementAt(index).userName + "</span>" + start + " " + playerName + "<br />";
            }
                if (j == 1)
                {
                    Round1.InnerHtml = header +  html;
                }
                else if (j == 2)
                {
                    Round2.InnerHtml = header + html;
                }
                else if (j == 3)
                {
                    Round3.InnerHtml = header + html;
                }
                else if (j == 4)
                {
                    Round4.InnerHtml = header + html; 
                }
                else if (j == 5)
                {
                    Round5.InnerHtml = header + html;
                }
                else if (j == 6)
                {
                    Round6.InnerHtml = header + html;
                }
                else if (j == 7)
                {
                    Round7.InnerHtml = header + html;
                }
                else if (j == 8)
                {
                    Round8.InnerHtml = header + html;
                }
                else if (j == 9)
                {
                    Round9.InnerHtml = header + html;
                }
                else if (j == 10)
                {
                    Round10.InnerHtml = header + html;
                }
                else if (j == 11)
                {
                    Round11.InnerHtml = header + html;
                }
                else if (j == 12)
                {
                    Round12.InnerHtml = header + html;
                }
                else if (j == 13)
                {
                    Round13.InnerHtml = header + html;
                }
                else if (j == 14)
                {
                    Round14.InnerHtml = header + html;
                }
                else if (j == 15)
                {
                    Round15.InnerHtml = header + html;
                }
                else if (j == 16)
                {
                    Round16.InnerHtml = header + html;
                }
        }
    }



    protected void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
    {
        
        if (e.Item.ItemType == ListItemType.Item
          || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int index = e.Item.ItemIndex;
            if (draftOrder.ElementAt(index).active == 1)
            {
                try
                {
                    HtmlGenericControl li = ((HtmlGenericControl)e.Item.FindControl("draftPick"));
                    li.Attributes.Add("class", "draftActive");

                }
                catch (Exception ex)
                {
                    Debug.WriteLine("fail");
                }
            }
            else
            {
                try
                {
                    HtmlGenericControl li = ((HtmlGenericControl)e.Item.FindControl("draftPick"));
                    li.Attributes.Remove("class");

                }
                catch (Exception ex)
                {
                    Debug.WriteLine("fail");
                }  
            }
           
        }
    }


    protected void onTeam_Selected(object sender, EventArgs e)
    {
        string selectedTeam = ((DropDownList)sender).SelectedValue.ToString();
        string selectedPos = PositionDD.SelectedValue.ToString();
        PlayerPanel.Controls.Clear();
        if (!selectedTeam.Equals("all"))
        {
            if (selectedPos.Equals("all"))
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                list(players, team);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, team, position);
            }
        }
        else
        {

            if (selectedPos.Equals("all"))
            {

                list(players);
            }
            else
            {
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, position);
            }
        }
    }


    protected void Pick_Click(object sender, EventArgs e)
    {
        string s = e.ToString();
        Debug.WriteLine(s + "  ---  ");
    }

    protected void onPosition_Selected(object sender, EventArgs e)
    {
        string selectedPos = ((DropDownList)sender).SelectedValue.ToString();
        string selectedTeam = TeamDD.SelectedValue.ToString();
        PlayerPanel.Controls.Clear();
        if (!selectedPos.Equals("all"))
        {
            if (selectedTeam.Equals("all"))
            {
                Position pos = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, pos);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, team, position);
            }
        }
        else
        {
            if (selectedTeam.Equals("all"))
            {
                list(players);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                list(players, team);
            }
        }
    }

    private void initPlayers(List<Player> players)
    {
        foreach (Player player in players)
        {
            player.setRealTeam();
        }
    }


    private void list(List<Player> players)
    {
        if (players != null)
        {
            int keeper = 0;
            int defender = 0;
            int midfielder = 0;
            int forward = 0;
            foreach (Player player in players)
            {
                if (player.position == Position.Keeper)
                {
                    if (keeper == 0)
                    {
                          
                        Panel keeperHeader = new Panel();
                        Label keeperLabel = new Label();
                        keeperHeader.ID = "keeperHeader";
                        keeperLabel.Text = "KEEPERS";
                         keeperHeader.Controls.Add(keeperLabel);
                        PlayerPanel.Controls.Add(keeperHeader);
                    }
                    keeper++;
                    
                    addPlayerControls(player);
                    
                }
            }

            foreach (Player player in players)
            {
                if (player.position == Position.Defender)
                {
                    if (defender == 0)
                    {
                        Panel defenderHeader = new Panel();
                        Label defenderLabel = new Label();
                        defenderHeader.ID = "defenderHeader";
                        defenderLabel.Text = "DEFENDERS";
                        defenderHeader.Controls.Add(defenderLabel);
                        PlayerPanel.Controls.Add(defenderHeader);
                    }
                    defender++;
                    addPlayerControls(player);
                }
            }

            foreach (Player player in players)
            {
                if (player.position == Position.Midfielder)
                {
                    if (midfielder == 0)
                    {
                        Panel midfielderHeader = new Panel();
                        Label midfielderLabel = new Label();
                        midfielderHeader.ID = "midfielderHeader";
                        midfielderLabel.Text = "MIDFIELDERS";
                        midfielderHeader.Controls.Add(midfielderLabel);
                        PlayerPanel.Controls.Add(midfielderHeader);
                    }
                    midfielder++;
                    addPlayerControls(player);
                }
            }

            foreach (Player player in players)
            {
                if (player.position == Position.Forward)
                {
                    if (forward == 0)
                    {
                        Panel forwardHeader = new Panel();
                        Label forwardLabel = new Label();
                        forwardHeader.ID = "forwardHeader";
                        forwardLabel.Text = "FORWARDS";
                        forwardHeader.Controls.Add(forwardLabel);
                        PlayerPanel.Controls.Add(forwardHeader);
                    }
                    forward++;
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void list(List<Player> players, Position position)
    {
        if (players != null)
        {
            foreach (Player player in players)
            {
                if (player.position.Equals(position))
                {
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void list(List<Player> players, Team team)
    {
        if (players != null)
        {

            int keeper = 0;
            int defender = 0;
            int midfielder = 0;
            int forward = 0;
            foreach (Player player in players)
            {
                if (player.team == team)
                {
                
                if (player.position == Position.Keeper)
                {
                    if (keeper == 0)
                    {
                        Panel keeperHeader = new Panel();
                        Label keeperLabel = new Label();
                        keeperHeader.ID = "keeperHeader";
                        keeperLabel.Text = "KEEPERS";
                        keeperHeader.Controls.Add(keeperLabel);
                        PlayerPanel.Controls.Add(keeperHeader);
                    }
                    keeper++;

                    addPlayerControls(player);


                }
                }
            }

            foreach (Player player in players)
            {
                if (player.team == team)
                {
                
                if (player.position == Position.Defender)
                {
                    if (defender == 0)
                    {
                        Panel defenderHeader = new Panel();
                        Label defenderLabel = new Label();
                        defenderHeader.ID = "defenderHeader";
                        defenderLabel.Text = "DEFENDERS";
                        defenderHeader.Controls.Add(defenderLabel);
                        PlayerPanel.Controls.Add(defenderHeader);
                    }
                    defender++;
                    addPlayerControls(player);
                }
                }
            }

            foreach (Player player in players)
            {
                if (player.team == team)
                {

                
                if (player.position == Position.Midfielder)
                {
                    if (midfielder == 0)
                    {
                        Panel midfielderHeader = new Panel();
                        Label midfielderLabel = new Label();
                        midfielderHeader.ID = "midfielderHeader";
                        midfielderLabel.Text = "MIDFIELDERS";
                        midfielderHeader.Controls.Add(midfielderLabel);
                        PlayerPanel.Controls.Add(midfielderHeader);
                    }
                    midfielder++;
                    addPlayerControls(player);
                }
                }
            }

            foreach (Player player in players)
            {
                if (player.team == team)
                {

                    if (player.position == Position.Forward)
                    {
                        if (forward == 0)
                        {
                            Panel forwardHeader = new Panel();
                            Label forwardLabel = new Label();
                            forwardHeader.ID = "forwardHeader";
                            forwardLabel.Text = "FORWARDS";
                            forwardHeader.Controls.Add(forwardLabel);
                            PlayerPanel.Controls.Add(forwardHeader);
                        }
                        forward++;
                        addPlayerControls(player);
                    }
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }


    

    private void addPlayerControls(Player player)
    {
        Label playerClickable = new Label();
        playerClickable.Text = player.playerName;
        bool posFilled = false;
        switch (player.position)
        {
            case Position.Keeper:
                if (currentTeam.keepers.Count > 1)
                {
                    posFilled = true;
                }
                break;
            case Position.Defender:
                if (currentTeam.defenders.Count > 5)
                {
                    posFilled = true;
                }
                break;
            case Position.Midfielder:
                if (currentTeam.midfielders.Count > 4)
                {
                    posFilled = true;
                }
                break;
            case Position.Forward:
                if (currentTeam.forwards.Count > 2)
                {
                    posFilled = true;
                }
                break;
            default:
                break;
        }


        playerClickable.CssClass = player.position.ToString() + " playerPickable"; //"player";
        playerClickable.ID = player.playerID.ToString();

        Panel testPanel = new Panel();
        testPanel.CssClass = "playerContent";

        Label teamName = new Label();
        Team team = ((Team)player.realTeamID);
        teamName.Text = team.ToString().Replace("_", " "); 
        teamName.CssClass = "playerTeam";

        Image playerImage = new Image();
        playerImage.ImageUrl = "../Images/Design/shiluett.png";
        playerImage.Width = Unit.Pixel(25);
        playerImage.Height = Unit.Pixel(25);
        playerImage.CssClass = "playerImage";

        Button draftButton = new Button();
        draftButton.CssClass = "checkmark pickable";
        draftButton.Text = "Draft player";
        draftButton.Visible = true;
        draftButton.ID = "playerClick_" + player.playerID.ToString();

        if (!posFilled)
        {
            draftButton.Command += new CommandEventHandler(this.PickPlayer);
            draftButton.CommandArgument = player.playerID.ToString();
        }

        testPanel.Controls.Add(playerImage);
        testPanel.Controls.Add(playerClickable);
        testPanel.Controls.Add(teamName);
        testPanel.Controls.Add(draftButton);  
        PlayerPanel.Controls.Add(testPanel);
    }

    void PickPlayer(Object sender, CommandEventArgs e)
    {
       

        if (lineup.Count < 16)
        {
            jsonParser.draftPlayer(user.username, user.password, e.CommandArgument.ToString());
            updateDraftDisplay();
        }
        else
        {
            Debug.WriteLine("Squad is full");
        }
    }

    void updateDraftDisplay()
    {
        PlayerPanel.Controls.Clear();
        players = jsonParser.getAvailablePlayers(user.username);
        getLineup();
        initPlayers(players);
        list(players);
        listDraftOrder();
        listPlayers();

        UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
        UpdatePanel.Update();

        UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional;
        UpdatePanel1.Update();

        UpdatePanel3.UpdateMode = UpdatePanelUpdateMode.Conditional;
        UpdatePanel3.Update();
    }




    private void list(List<Player> players, Team team, Position position)
    {
        if (players != null)
        {
            foreach (Player player in players)
            {
                if (player.team.Equals(team) && player.position.Equals(position))
                {
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void addTeamsToDropdown()
    {
        Array itemValues = System.Enum.GetValues(typeof(Team));
        Array itemNames = System.Enum.GetNames(typeof(Team));

        ListItem item2 = new ListItem("All teams", "all");
        TeamDD.Items.Add(item2);

        for (int i = 0; i <= itemNames.Length - 1; i++)
        {
            ListItem item = new ListItem(removeUnderscore(itemNames.GetValue(i).ToString()), itemValues.GetValue(i).ToString());
            TeamDD.Items.Add(item);
        }
    }

    private void addPositionsToDropdown()
    {
        Array itemValues = System.Enum.GetValues(typeof(Position));
        Array itemNames = System.Enum.GetNames(typeof(Position));

        ListItem item2 = new ListItem("All players", "all");
        PositionDD.Items.Add(item2);

        for (int i = 0; i <= itemNames.Length - 1; i++)
        {
            ListItem item = new ListItem(removeUnderscore(itemNames.GetValue(i).ToString()), itemValues.GetValue(i).ToString());
            PositionDD.Items.Add(item);
        }
    }

    private string removeUnderscore(string st)
    {
        st = st.Replace('_', ' ');
        return st;
    }
    
}